#!/usr/bin/python
#coding:utf8
'''
Flyweight
'''

# 构建享元工厂类维护内部状态
class Goods:
    def __init__(self, uid, scale):
        self.uid = uid
        self.scale = scale
    
    def show(self):
        print("uid:%s, scale:%s" % (self.uid, self.scale))

class goodsFactory:
    def __init__(self):
        self.goods_pool = {}

    def getGoods(self, uid, scale):
        if (uid,scale) not in self.goods_pool.keys():
            self.goods_pool[(uid,scale)] = Goods(uid, scale)
        return self.goods_pool[(uid,scale)]

# 用户类维护外部信息，通过工厂类获取共享对象
class Customer:
    order = []
    def __init__(self, name, goods_factory):
        self.name = name
        self.goods_factory = goods_factory

    def buyGoods(self, uid, scale):
        goods = self.goods_factory.getGoods(uid, scale)
        Customer.order.append((self.name, goods))

    @classmethod
    def showOrder(cls):
        for name, goods in cls.order:
            print("%s buy goods(id:%s)" % (name, id(goods)))

if __name__ == "__main__":
    goods_factory = goodsFactory()
    customer1 = Customer("customer1", goods_factory)
    customer2 = Customer("customer2", goods_factory)
    customer1.buyGoods("001", "A")
    customer1.buyGoods("002", "B")
    customer2.buyGoods("001", "A")
    customer2.showOrder()




    
